package com.zhugang.week13.sort;

/**
 * @program algorithms
 * @description: insertionSortList
 * @author: chanzhugang
 * @create: 2022/10/19 15:45
 */
public class InsertionSortList {

    /**
     * 147 对链表进行插入排序
     * https://leetcode.cn/problems/insertion-sort-list/
     *
     * @param head
     * @return
     */
    public ListNode insertSortList(ListNode head) {
        // 链表插入排序，比数组插入排序难
        ListNode dummyHead = new ListNode(Integer.MIN_VALUE, null);
        ListNode p = head;
        while (p != null) {
            ListNode tempNext = p.next;
            // 将当前节点插入到有序列表正确的位置
            ListNode q = dummyHead;
            while (q.next != null && q.next.val <= p.val) {
                q = q.next;
            }
            // 找到 q.next.val > p.val, 即q是p的前置节点, p插入到q后面

            // p 插入到q后面，画个图就知道了
            // p指向q的下一个节点； q指向p
            p.next = q.next;
            q.next = p;
            p = tempNext;
        }
        return dummyHead.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}